import { Injectable } from '@nestjs/common';
import { RedisService } from 'nestjs-redis';

@Injectable()
export class CommonRedisService {
    public client;
    constructor(private redisServ: RedisService) {
        this.getClient()
    }

    // 获取redis client对象
    private async getClient() {
        this.client = await this.redisServ.getClient();
    }

    // 设置redis的值
    async set(key: string, value: any, seconds: number = 60) {
        if (typeof value === 'object' && value !== null) {
            value = JSON.stringify(value);
        } else {
            value = String(value);
        }
        return await this.client.set(key, value, 'EX',seconds); 
    }
    
    // 读取值
    async get(key: string) {
        var data = await this.client.get(key);           
        if (!data) return;
        try {
            data = JSON.parse(data);
        } catch (error) {
            
        }
        
        return data;       
    }

}
